package com.leyou.controller;

import com.leyou.common.exceptions.LyException;
import com.leyou.dto.UserDTO;
import com.leyou.pojo.TbUser;
import com.leyou.service.TbUserService;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author: guojy
 * @date: 2020/3/17 18:27
 * @Description:
 * @version: 1.0
 */
@RestController
public class UserController {
    @Autowired
    private TbUserService tbUserService;

    /**
     * 验证手机号或者用户名是否存在
     *
     * @param data 手机号或者用户名
     * @param type 1，用户名；2，手机
     */
    @ApiOperation(value = "校验用户名数据是否可用，如果不存在则可用")
    @ApiResponses({
            @ApiResponse(code = 200, message = "校验结果有效，true或false代表可用或不可用"),
            @ApiResponse(code = 400, message = "请求参数有误，比如type不是指定值")}
    )
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserData(
            @ApiParam(value = "要校验的数据", example = "jgybzx") @PathVariable("data") String data,
            @ApiParam(value = "数据类型，1：用户名，2：手机号", example = "1") @PathVariable("type") Integer type) {
        Boolean flag = tbUserService.checkUserData(data, type);
        return ResponseEntity.ok(flag);
    }

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @ApiOperation("发送短信验证码")
    @PostMapping("code")
    public ResponseEntity<Void> sendCode(@ApiParam(value = "真实手机号") @RequestParam("phone") String phone) {
        tbUserService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户注册
     *
     * @param user 用户信息
     * @param code 验证码
     */
    @ApiOperation("用户注册")
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid TbUser user, BindingResult bindingResult,
                                         @RequestParam("code") String code) {

        // Hibernate Validator  处理错误信息
        if (bindingResult.hasErrors()) {
            String msg = bindingResult.getFieldErrors().
                    stream().
                    map(DefaultMessageSourceResolvable::getDefaultMessage).
                    collect(Collectors.joining("|"));
            throw new LyException(400, msg);
        }
        tbUserService.register(user, code);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 登录时，根据用户名密码查询用户，反向解密的过程
     *
     * @param username 用户名
     * @param password 密码
     */
    @GetMapping("query")
    public ResponseEntity<UserDTO> queryUserByUsernameAndPassword(
            @RequestParam("username") String username, @RequestParam("password") String password) {
        UserDTO userDTO = tbUserService.queryUserByUsernameAndPassword(username, password);
        return ResponseEntity.ok(userDTO);
    }

}
